package com.mjlf.test_shiro.shiro;

import com.mjlf.test_shiro.entity.Person;
import com.mjlf.test_shiro.service.PermissionService;
import com.mjlf.test_shiro.service.PersonService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @ClassName: UserRealm
 * @Author: majun
 * @CreateDate: 2018/10/17 16:29
 * @Version: 1.0
 * @Description: TODO
 */


public class UserRealm extends AuthorizingRealm {

    @Autowired
    private PersonService personService;

    @Autowired
    private PermissionService permissionService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前用户
        Person person = (Person)principalCollection.getPrimaryPrincipal();

        //获取权限
        List<String> permissions = permissionService.getPermissions(person.getName());

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        info.addStringPermissions(permissions);
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        Person person = personService.getPerson(token.getUsername());
        if(person == null){
            return null;
        }
        return new SimpleAuthenticationInfo(person, person.getPassword().toCharArray(), getName());
    }
}
